//
//  ViewController.m
//  DrawLine
//
//  Created by lhy on 2021/1/21.
//

#import "LMRPDFViewVC.h"
#import "LHYSignAlertView.h"
#import "LHYImageCopyView.h"
#import "LHYTextFieldCopyView.h"

#import "LHYPDFAnnotation.h"

#import "FileUtil.h"//文件管理
#import "LHYDefine.h"//宏定义
#import "LHYPDFEditSignAddListView.h"

@interface LMRPDFViewVC () <PDFDocumentDelegate, UIDocumentPickerDelegate>

typedef enum : NSUInteger {
    TypeImageTitle,
    TypeTitleBtn,
    TypeShowSignViewBtn,        //添加或移除签名  进入签名页
    TypeShowSignListViewBtn,    //添加或移除签名  进入签名列表页
} toolPopoverType;

#define PDF_FILE_NAME           @"PDFKit.pdf"
#define PDF_pageCurrentNum      ([self.qlView getCurrentPageCount] - 1)
#define PDF_pageHeight          [self.qlView getPageHeight]

#define PDF_addType             1       //0、drawingView addSubview（该方式添加注释偏移量大，未解决）; 1、pdfView.documentView addSubview

typedef NS_ENUM(NSInteger, LHYAnnoType)
{
    LHYAnnoText = 0,      //文本注释
    LHYAnnoDrawLine = 1,  //任意画线
    LHYAnnoDrawImage = 2, //图片注释
};
/// 注释
@property (nonatomic, strong) LHYPDFAnnotation *annotation;
/// 文本输入组
@property (nonatomic, strong) NSMutableArray *annoTextArr;
/// 签名图片数组
@property (nonatomic, strong) NSMutableArray *annoImageArr;
/// 生成的签名图片
@property (nonatomic, strong) LHYImageCopyView *signImageView;
/// 文本
@property (nonatomic, strong) LHYTextFieldCopyView *textFieldView;
/// 复制后的偏移量
@property (nonatomic, assign) NSUInteger copyOffset;
/// 复制的签名图片
@property (nonatomic, strong) UIImage *imageCopy;
/// 复制的文本
@property (nonatomic, copy) NSString *strCopy;

/// 编辑btn
@property (nonatomic, strong) UIButton *btnEdit;
/// 画线btn
@property (nonatomic, strong) UIButton *btnDraw;
/// 清空btn
@property (nonatomic, strong) UIButton *btnClear;
/// 是否清空当前页注释
@property (nonatomic, assign) BOOL isClearedCurrentPageAnno;

@property (strong, nonatomic) UIDocumentPickerViewController *dpvc;

@property (strong, nonatomic) PDFPage *currentPage;

@end

@implementation LMRPDFViewVC

@synthesize signImageView, qlView, annotation, textFieldView;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.whiteColor;
    
    //    PDFView
    [self initQLPDFView];
    
    //    导航栏
    [self initNavItems];
    
    //    底部toolView
    [self showToolView];
    
    //    添加PDFView的通知监听
    [self addNotificationObserver];
}


- (void)initQLPDFView {
    
    self.qlView = [[QLPDFView alloc] initWithFrame:CGRectMake(0, 0, kScreenSizeWidth, kScreenSizeHeight - kNavBarAndStatusBarHeight)];
    [self.view addSubview:self.qlView];
    
    //    保存新PDF的路径
    NSString *pdfPath = [FileUtil getFilePath:PDF_FILE_NAME];
    if (![FileUtil isFileExisted:PDF_FILE_NAME]) {
        //      若无新PDF,  则展示本地原始PDF
        pdfPath = [[NSBundle mainBundle] pathForResource:@"Document" ofType:@"pdf"];
    }
    self.qlView.pdfPath = pdfPath;
    // 画笔颜色
    self.qlView.lineColor = UIColor.blackColor;
    // 画笔宽度
    self.qlView.lineWidth = 2;
    // pdfView
    self.qlView.pdfView.frame = self.qlView.bounds;
    // 页码
    self.qlView.labelStr = [NSString stringWithFormat:@"%ld / %ld", [self.qlView getCurrentPageCount], [self.qlView getPageCount]];
}

- (void)initNavItems {
    UIBarButtonItem *addBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPDFDocumentFromFiles)];
    
    UIBarButtonItem *itemBtnEdit = [[UIBarButtonItem alloc] initWithCustomView:self.btnEdit];
    UIBarButtonItem *itemBtnDraw = [[UIBarButtonItem alloc] initWithCustomView:self.btnDraw];
    UIBarButtonItem *itemBtnClear = [[UIBarButtonItem alloc] initWithCustomView:self.btnClear];
    
    self.navigationItem.leftBarButtonItems = @[addBarButtonItem,
                                               itemBtnEdit,
                                               itemBtnDraw];
    
    self.navigationItem.rightBarButtonItems = @[itemBtnClear];
}

/// 添加PDFView的通知监听
- (void)addNotificationObserver {
    
    //放大缩小通知
    [[NSNotificationCenter defaultCenter] addObserverForName:PDFViewScaleChangedNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        
        if (self.qlView.pdfView.scaleFactor > 2) {
            NSLog(@"放大缩小通知");
            [UIView animateWithDuration:0.1 animations:^{
                self.qlView.pdfView.scaleFactor = 2;
            }];
        }
    }];
    //滚动视图滚动到新页面边界时的通知
    [[NSNotificationCenter defaultCenter] addObserverForName:PDFViewVisiblePagesChangedNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        
        //        NSLog(@"滚动视图滚动到新页面边界时的通知:     %@", note);
    }];
    //当一个新页面 page成为当前页面时的通知
    [[NSNotificationCenter defaultCenter] addObserverForName:PDFViewPageChangedNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        
        // 页码
        self.qlView.labelStr = [NSString stringWithFormat:@"%ld / %ld", [self.qlView getCurrentPageCount], [self.qlView getPageCount]];
        //        NSLog(@"当一个新页面成为当前页面时的通知。:     %@", note);
        //        NSLog(@"%@", note.object);
        //        NSLog(@"%@", note.name);
        //        NSLog(@"%@", note.userInfo);
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"PDFMoreToolDidSelectRowNotification" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        // 下标
        NSInteger index = [note.userInfo[@"index"] integerValue];
        // 气泡种类
        NSInteger type = [note.userInfo[@"type"] integerValue];
        
        //        获取当前page
        //        ...
        
        // 获取当前page页码
        NSString *str = self.qlView.pdfView.currentPage.label;
        NSLog(@"page页码：%@", str);
        
        if (type == TypeImageTitle) {
            if (index == 0) {
                //文本
                [self addTextFieldWithBounds:CGRectZero text:note.userInfo[@"text"]];
            }
        } else if (type == TypeTitleBtn) {
            [self addTextFieldWithBounds:CGRectZero text:note.userInfo[@"text"]];
        } else if (type == TypeShowSignViewBtn) {
            [self showSignView];
        } else if (type == TypeShowSignListViewBtn) {
            [self showSignListView];
        }
    }];
}

#pragma mark - 底部toolView
/// 底部toolView
- (void)showToolView {
    self.toolView = [[[NSBundle mainBundle] loadNibNamed:@"LHYPDFEditToolView" owner:self options:nil] lastObject];
    self.toolView.frame = CGRectMake(100, kScreenSizeHeight - 130, kScreenSizeWidth - 200, 100);
    self.toolView.viewController = self;
    
    WeakSelf;
    // 画笔颜色
    self.toolView.getDrawColorBlock = ^(UIColor * _Nonnull color) {
        StrongSelf;
        strongSelf.qlView.lineColor = color;
    };
    // 画笔宽度
    self.toolView.getDrawWidthBlock = ^(NSInteger width) {
        StrongSelf;
        strongSelf.qlView.lineWidth = width;
    };
}
/// 签名列表页
- (void)showSignListView {
    LHYPDFEditSignAddListView *listView = [LHYPDFEditSignAddListView shareSignAddListView];
    [listView show];
}

- (void)addPDFDocumentFromFiles {
    
    NSArray *types = @[@"public.composite-content",
                       @"com.adobe.pdf"];
    self.dpvc = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
    // UIDocumentPickerModeOpen 和import一样，open同样从文件提供者那里获得数据并导入我们的host app，只是不同的是，这些数据没有被拷贝一份至我们的host app,数据还在原处。例如，你或许在音乐播放器、视频播放器，再或者图像编辑器中使用该方式。
    
    self.dpvc.delegate = self;
    
    [self updateICloudPDF];
    
    [self.navigationController presentViewController:self.dpvc animated:YES completion:nil];
}

/// 更新本地源文件（iCloud文件）
- (void)updateICloudPDF {
    
    if (self.qlView.pdfView.document) {
        [self.qlView.pdfView.document writeToURL:self.qlView.pdfView.document.documentURL];
    }
}

#pragma mark - 添加注释
/// 添加注释
- (void)addAnnoWithAnnoType:(LHYAnnoType)type {
    
    PDFRect pageBounds = [self.qlView.pdfView.currentPage boundsForBox:kPDFDisplayBoxCropBox];
    
    switch (type) {
        case LHYAnnoText:{
            //循环添加所有的文本注释
            for (LHYTextFieldCopyView *textField in self.annoTextArr) {
                //旧方法： 绘制注释
                //                annotation = [[LHYPDFAnnotation alloc] initWithBounds:rect forType:PDFAnnotationSubtypeInk withProperties:@{@"textFieldView":textField}];
                //                [page addAnnotation:self.annotation];
                
                //新方法： 原生方法设置注释(文字基本解决，图片暂未解决)
                CGRect textFieldNameBounds = CGRectMake(textField.frame.origin.x,
                                                        pageBounds.size.height - (textField.frame.origin.y + textField.frame.size.height - textField.pageIndex * pageBounds.size.height),
                                                        textField.frame.size.width - 30,//注释宽度 微调
                                                        textField.frame.size.height);
                //    注释
                PDFAnnotation *anno = [[PDFAnnotation alloc] initWithBounds:textFieldNameBounds forType:PDFAnnotationSubtypeWidget withProperties:nil];
                //    注释小组件的类型 (类型里面没有图片或者label文字)
                anno.widgetFieldType = PDFAnnotationWidgetSubtypeText;
                //                anno.backgroundColor = [UIColor colorWithWhite:0.4 alpha:0.3];
                anno.font = textField.font;
                anno.widgetStringValue = textField.text;
                anno.multiline = YES;   // 设置注释文本多行
                anno.readOnly = YES;    // 设置注释不可编辑
                
                self.currentPage = [self.qlView.pdfView.document pageAtIndex:textField.pageIndex];
                [self.currentPage addAnnotation:anno];
                
                [textField removeFromSuperview];
            }
            [self.annoTextArr removeAllObjects];
        }
            break;
        case LHYAnnoDrawLine:{
            
        }
            break;
        case LHYAnnoDrawImage:{
            //循环添加所有的图片注释
            for (LHYImageCopyView *imageView in self.annoImageArr) {
                //旧方法： 绘制注释
                self.currentPage = [self.qlView.pdfView.document pageAtIndex:imageView.pageIndex];
                
                annotation = [[LHYPDFAnnotation alloc] initWithBounds:pageBounds forType:PDFAnnotationSubtypeInk withProperties:@{@"imageView":imageView}];
                
                [self.currentPage addAnnotation:self.annotation];
                
                [imageView removeFromSuperview];
            }
            
            [self.annoImageArr removeAllObjects];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 编辑/清空/保存 画线/注释

- (void)actionEdit {
    _btnEdit.selected = !_btnEdit.selected;
    
    [_btnEdit setTitle:_btnEdit.selected? @"保存" : @"开始绘制" forState:UIControlStateNormal];
    [_btnEdit setTitleColor:_btnEdit.selected? UIColor.systemBlueColor : UIColor.redColor forState:UIControlStateNormal];
    
    self.btnClear.hidden = !_btnEdit.selected;
    self.btnDraw.hidden = !_btnEdit.selected;
    
    if (_btnEdit.selected) {
        
        [self enterDrawingWithBtn:self.btnDraw];
        [self.toolView show];
    } else {
        
        [self closeDrawingWithBtn:self.btnDraw];
        [self.toolView hide];
        // 退出绘制，立即保存
        [self actionSave];
    }
}

/// 画线 / 注释
- (void)actionDraw {
    if ([self.btnDraw.titleLabel.text isEqualToString:@"开始绘制"]) {
        //画线
        [self enterDrawingWithBtn:self.btnDraw];
    } else {
        //注释
        [self closeDrawingWithBtn:self.btnDraw];
    }
}

/// 保存新的 PDF
- (void)actionSave {
    NSLog(@"self.qlView isNeedSave:  %d",       [self.qlView isNeedSave]);
    NSLog(@"self.isClearedCurrentPageAnno:  %d", self.isClearedCurrentPageAnno);
    
    if (self.annoTextArr.count || self.annoImageArr.count || self.isClearedCurrentPageAnno || [self.qlView isNeedSave]) {
        
        [self addAnnoWithAnnoType:LHYAnnoText];
        [self addAnnoWithAnnoType:LHYAnnoDrawImage];
        
        BOOL createSuccess = [FileUtil createFileAtPath:PDF_FILE_NAME];
        NSString *path = [FileUtil getFilePath:PDF_FILE_NAME];
        
        if (createSuccess) {
            NSLog(@"文件路径创建成功");
        } else {
            NSLog(@"文件路径已存在");
        }
        WeakSelf;
        [self.qlView saveToFile:path block:^(BOOL suc) {
            NSLog(@"PDF保存状态：%d", suc);
            if (suc) {
                weakSelf.isClearedCurrentPageAnno = NO;
            }
        }];
    } else {
        NSLog(@"PDF文件未更改，无需再次保存");
    }
}

- (void)actionClear {
    //循环删除所有的文本obj
    for (LHYTextFieldCopyView *textField in self.annoTextArr) {
        
        [textField removeFromSuperview];
    }
    [self.annoTextArr removeAllObjects];
    
    //循环删除所有的图片obj
    for (LHYImageCopyView *imageView in self.annoImageArr) {
        
        [imageView removeFromSuperview];
    }
    [self.annoImageArr removeAllObjects];
    
    NSMutableArray *arr = [NSMutableArray arrayWithArray:self.qlView.pdfView.currentPage.annotations];
    //循环删除所有的注释
    for (LHYPDFAnnotation *anno in arr) {
        [self.qlView.pdfView.currentPage removeAnnotation:anno];
    }
    //    此时可以保存
    self.isClearedCurrentPageAnno = YES;
}

- (void)enterDrawingWithBtn:(UIButton *)drawBtn {
    // 退出绘制状态
    [self.qlView enterDrawingStatus];
    [drawBtn setTitle:@"查看" forState:UIControlStateNormal];
}

- (void)closeDrawingWithBtn:(UIButton *)drawBtn  {
    // 退出绘制状态
    [self.qlView exiteDrawingStatus];
    [drawBtn setTitle:@"开始绘制" forState:UIControlStateNormal];
}

#pragma mark - 初始化与复制 imageView
/// 打开签名 alert
- (void)showSignView {
    LHYSignAlertView *sign = [LHYSignAlertView shareSignView];
    sign.center = self.view.center;
    __weak typeof(self) weakSelf = self;
    sign.getSignImageBlock = ^(UIImage * _Nonnull signImage) {
        
        [weakSelf addSignImageView];
        weakSelf.signImageView.image = signImage;
    };
    [sign show];
}

- (void)addSignImageView {
    
    _copyOffset+= 10;
    _copyOffset = _copyOffset < 100 ? _copyOffset : 0;
    
    signImageView = [[LHYImageCopyView alloc] init];
    signImageView.frame = CGRectMake(25 + _copyOffset,
                                     PDF_pageCurrentNum * PDF_pageHeight + _copyOffset + 200 + _copyOffset,
                                     130,
                                     100);
    signImageView.image = self.imageCopy;
    WeakSelf;
    signImageView.getCopyImageBlock = ^(UIImage * _Nonnull copyImage) {
        StrongSelf;
        strongSelf.imageCopy = copyImage;
        [strongSelf addSignImageView];
    };
    signImageView.removeImageBlock = ^(LHYImageCopyView * _Nonnull imageView) {
        StrongSelf;
        [strongSelf.annoImageArr removeObject:imageView];
    };
    if (PDF_addType) {
        [self.qlView.pdfView.documentView addSubview:signImageView];
    } else {
        [self.qlView.drawingView addSubview:signImageView];
    }
    
    signImageView.pageIndex = PDF_pageCurrentNum;
    [self.annoImageArr addObject:signImageView];
    
    // 添加注释，关闭绘制
    [self closeDrawingWithBtn:self.btnDraw];
}

#pragma mark - 初始化与复制 textField

- (void)addTextFieldWithBounds:(CGRect)bounds text:(NSString *)text {
    
    _copyOffset+= 10;
    _copyOffset = _copyOffset < 100 ? _copyOffset : 0;
    
    bounds = bounds.size.width ? bounds : CGRectMake(25 + _copyOffset,
                                                     PDF_pageCurrentNum * PDF_pageHeight + _copyOffset,
                                                     kScreenSizeWidth / 4,
                                                     34);
    
    textFieldView = [[LHYTextFieldCopyView alloc] initWithFrame:bounds
                                                    placeholder:nil
                                                          clear:YES
                                                       leftView:nil
                                                       fontSize:17];
    textFieldView.text = text ? text : @"文本";
    
    WeakSelf;
    textFieldView.getCopyTextBlock = ^(NSString *copyText, CGRect bounds) {
        StrongSelf;
        [strongSelf addTextFieldWithBounds:bounds text:copyText];
    };
    textFieldView.removeTextBlock = ^(LHYTextFieldCopyView * _Nonnull textField) {
        StrongSelf;
        [strongSelf.annoTextArr removeObject:textField];
    };
    textFieldView.pageIndex = PDF_pageCurrentNum;
    [self.annoTextArr addObject:textFieldView];
    
    if (PDF_addType) {
        [self.qlView.pdfView.documentView addSubview:textFieldView];
    } else {
        [self.qlView.drawingView addSubview:textFieldView];
    }
    // 添加注释，关闭绘制
    [self closeDrawingWithBtn:self.btnDraw];
}

#pragma mark - DocumentPickerControllerDelegate

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    //获取授权
    NSLog(@"urls.firstObject:      %@", urls.firstObject);
    
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    
    if (fileUrlAuthozied) {
        PDFDocument * document = [[PDFDocument alloc] initWithURL:urls.firstObject];
        self.qlView.pdfView.document = document;
        self.qlView.pdfView.scaleFactor = self.qlView.pdfView.scaleFactorForSizeToFit;
    } else {
        NSLog(@"授权失败");
    }
}

#pragma mark - PDFDocumentDelegate  (加载自定义 page, 实现水印等)
//- (Class)classForPage {
//    return LHYPDFPage.class;
//}

#pragma mark - 懒加载

- (NSMutableArray *)annoTextArr {
    if (!_annoTextArr) {
        _annoTextArr = [[NSMutableArray alloc] init];
    }
    return _annoTextArr;
}

- (NSMutableArray *)annoImageArr {
    if (!_annoImageArr) {
        _annoImageArr = [[NSMutableArray alloc] init];
    }
    return _annoImageArr;
}

- (UIButton *)btnEdit {
    if (!_btnEdit) {
        _btnEdit = [[UIButton alloc] init];
        [_btnEdit addTarget:self action:@selector(actionEdit) forControlEvents:UIControlEventTouchUpInside];
        [_btnEdit setTitleColor:UIColor.redColor forState:UIControlStateNormal];
        [_btnEdit setTitle:@"开始绘制" forState:UIControlStateNormal];
    }
    return _btnEdit;
}
- (UIButton *)btnDraw {
    if (!_btnDraw) {
        _btnDraw = [[UIButton alloc] init];
        [_btnDraw addTarget:self action:@selector(actionDraw) forControlEvents:UIControlEventTouchUpInside];
        [_btnDraw setTitleColor:UIColor.redColor forState:UIControlStateNormal];
        [_btnDraw setTitle:@"开始绘制" forState:UIControlStateNormal];
        _btnDraw.hidden = YES;
    }
    return _btnDraw;
}

- (UIButton *)btnClear {
    if (!_btnClear) {
        _btnClear = [[UIButton alloc] init];
        _btnClear.hidden = YES;
        [_btnClear addTarget:self action:@selector(actionClear) forControlEvents:UIControlEventTouchUpInside];
        [_btnClear setTitleColor:UIColor.redColor forState:UIControlStateNormal];
        [_btnClear setTitle:@"清空当前页" forState:UIControlStateNormal];
    }
    return _btnClear;
}



- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    NSLog(@"didReceiveMemoryWarning");
}

@end
